package org.aileen.springbook.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.aileen.springbook.Constant.Constant;
import org.aileen.springbook.model.Result;
import org.aileen.springbook.model.UserInfo;
import org.aileen.springbook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RequestMapping("/user")
@RestController
public class UserController {
    //注入Service层
    @Autowired
    UserService userService;

    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(String userName, String password, HttpSession session) {
        //1.参数校验
        //2.验证用户名和密码
        //3.存Session
            //使用java库中的StringUtils来帮助我们判断
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码不能为空");
        }

        //根据用户名查询用户信息,判断密码是否正确
        UserInfo userInfo = userService.queryUserByName(userName);//查询到用户信息
        //进行用户信息的校验
        if(userInfo == null || userInfo.getId() < 0) {
            return Result.fail("用户不存在");
        }
        if(!password.equals(userInfo.getPassword())) {
            return Result.fail("账号或密码错误");
        }
        //      将用户除了密码之外的信息存入Session中
        userInfo.setPassword("");
        session.setAttribute(Constant.USER_SESSION_KEY,userInfo);//将"USER_SESSION_KEY"定义为常量Constant
        return Result.success("");//登录成功,返回空数据


////        //未学数据库操作,暂时硬编码
//        //写死 userName  = zhangsna , password = 12345
//        if(!"zhangsan".equals(userName) || !"123456".equals(password)){
//            return "账号或密码错误";
//        } //现在学了数据库,就可从数据库进行验证-> 创建Service层:专门用于用户登录验证

//        之前存储session
       // session.setAttribute("userName", userName);

    }
}
